﻿using System;
using System.IO;

namespace Actya.Core.Util
{
	public static class FileUtil
	{
		/// <summary>
		/// Checks if the given directory is writable.
		/// </summary>
		/// <param name="physicalDirectory"></param>
		/// <returns></returns>
		public static bool CheckIfDirectoryIsWritable(string physicalDirectory)
		{
			// Check if the given directory is writable by creating a dummy file.
			string fileName = Path.Combine(physicalDirectory, "dummy.txt");

			try
			{
				using (var sw = new StreamWriter(fileName))
				{
					// Add some text to the file.
					sw.WriteLine("DUMMY");
					sw.Flush();
				}
				// Delete temporary file if it was successfully created.
				if (File.Exists(fileName))
				{
					File.Delete(fileName);
					return true;
				}
				return false;
			}
			catch (UnauthorizedAccessException)
			{
				return false;
			}
		}
	}
}
